const app = require('express').Router()

// 获取所有的服务信息
app.get('/getAllDemService', (req, res) => {
  const query = `SELECT * FROM ${global.myConfig.pool.serviceTable} ORDER BY created_at DESC`;
  global.pool.query(query, (err, result) => {
    if (err) {
      console.error('查询数据出错:', err);
      res.status(500).send('服务器错误');
      return;
    }
    res.json(result.rows);
  });
});

// 根据id查询服务信息
app.get('/getInfoById', (req, res) => {
  const id = req.query.id
  const query = `SELECT * FROM ${global.myConfig.pool.serviceTable} WHERE id='${id}'`;
  global.pool.query(query, (err, result) => {
    if (err) {
      console.error('查询数据出错:', err);
      res.status(500).send('服务器错误');
      return;
    }
    res.json(result.rows);
  });
})

// 插入服务信息
app.post('/insertDemService', (req, res) => {
  let { id, name, info, path, type, section } = req.body;
  const created_at = new Date().getTime()
  const insterQuery = `INSERT INTO ${global.myConfig.pool.serviceTable} (id,name,info,path,type,section,created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)`;
  if (section == undefined) {
    section = 0
  }
  const values = [id, name, info, path, type, section, created_at]
  global.pool.query(insterQuery, values, (err, result) => {
    if (err) {
      console.error('插入数据出错:', err);
      res.status(500).send('服务器错误');
      return;
    }
    res.json({
      status: 200,
      msg: '保存成功'
    });
  });
})
// 删除服务信息
app.get('/deleteServiceInfo', (req, res) => {
  const id = req.query.id
  const deleteQuery = `DELETE FROM ${global.myConfig.pool.serviceTable} WHERE id='${id}'`
  global.pool.query(deleteQuery, (err, result) => {
    if (err) {
      console.error('删除数据出错:', err);
      res.status(500).send('删除失败');
      return
    }
    global.pool.query(`DELETE FROM ${global.myConfig.pool.logTable} WHERE id='${id}'`, (err, log) => {
      if (err) {
        console.error('删除日志出错:', err);
        res.status(500).send('删除失败');
        return
      }
      res.json({
        status: 200,
        msg: '删除成功'
      })
    })
  })
})
// 根据id查询日志
app.get('/getLogById', (req, res) => {
  const id = req.query.id
  const logQuery = `SELECT log FROM ${global.myConfig.pool.logTable} WHERE id = '${id}' ORDER BY "time" ASC`
  global.pool.query(logQuery, (err, result) => {
    if (err) {
      console.error('查询日志出错:', err);
      res.status(500).send('日志查询失败');
      return
    }
    global.pool.query(`select section from ${global.myConfig.pool.serviceTable} where id = '${id}'`, (err, info) => {
      if (err) {
        console.error('查询任务进度失败', err);
        res.status(500).send('日志查询失败')
        return
      }
      res.json({
        section: info.rows[0].section,
        logs: result.rows
      })
    })
  })
})


module.exports = app;